//
//  LoginController.swift
//  SmartCheckIn
//
//  Created by Cidy Chou on 2017/9/4.
//  Copyright © 2017年 CidyChou. All rights reserved.
//
import Foundation
import UIKit
import Security

///  登陆／注册Controller

class LoginController : UIViewController {

    var navigationBar : UINavigationBar! //标题栏
    
    @IBOutlet weak var lbTitle: UILabel!
    @IBOutlet weak var btnCode: UIButton!     //获取验证码按钮
    @IBOutlet weak var tfCode: UITextField!   //验证码
    @IBOutlet weak var tfPhone: UITextField!    // 手机号码
    @IBOutlet weak var btnNext: UIButton!       // 继续按钮
    
    //创建活动指示器
    var aiv = UIActivityIndicatorView()

    var rCode :String = "12345" //默认验证码 ，用于通过苹果测试
    let defaults = UserDefaults.standard // userDefault  用于保存 用户信息、服务器信息
    //var severDic = Dictionary<String, Any>()  //  用户选择后的服务器信息
    var severDic : [Any]? = nil  //  用户选择后的服务器信息
    
    var mOrder : Int  = 5
    
    override func viewDidLoad() {
        
        getServerList()
        
        
    }
   
    ///
    func initView(ord : Int){
        createActivityIndicatorView()
        
        //设置状态栏颜色
        setStatusBarBackgroundColor(color: UIColor(red: 27/255, green: 130/255, blue: 210/255, alpha: 1),titleName: severDic![5] as! String)
        
        //deleteKeyChain()
        //iphone 8 16034A1F-3E97-43A7-9D6B-C63AC78C128E
        //iphone 6 AFA48523-1114-4EB9-B107-A5DD0E1C5759
        // ipod 4125C207-D1AC-4A4D-BB0A-B5E0B9F665BD
        print("initKeyChain:",initKeyChain())  //通过keyChain存放UUID。确保用户卸载／更新app后UUID不变
        
        lbTitle.backgroundColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1)
        lbTitle.text = "请输入以下信息，完成验证"
        
        btnCode.setTitle("获取验证码", for: .normal)
        
        //TextField 样式为下划线
        initTextField(textField: tfPhone)
        initTextField(textField: tfCode)
        
        
        tfPhone.rightView  = btnCode
        tfPhone.rightViewMode = UITextFieldViewMode.always
        
        tfPhone.placeholder = "请输入手机号码"
        //let ord = 6
        if ord == 5  || ord  == 6 {
            tfCode.placeholder = "请输入学籍号"
            btnCode.isHidden = true
           }else{
            tfCode.placeholder = "请输入验证码"
        }
        
        
        //btnNext 样式
        btnNext.backgroundColor = UIColor(red: 27/255, green: 130/255, blue: 210/255, alpha: 1)
        btnNext.setTitleColor(UIColor.white, for: .normal)
        
        
//        activityIndicator.center = self.view.center
//        self.view.addSubview(activityIndicator)
        self.stop()
        
    }
    
    
    ///  获取验证码
    @IBAction func getCode(sender: CountDownBtn) {
        
        let userPhone = tfPhone.text
        if RegexUtils().doMatch(input: userPhone!,regex: "^1[0-9]{10}$"){
            // 设置动画类型,可以不写,默认没有动画效果
            //sender.animaType = .Rotate
            
            //初始化
            let emptyDict : [String: String] = ["phone":userPhone!]
            
            let webService = WebServiceUtils(methodName: "sendVerificationCode", paramsDict: emptyDict,resultName: "sendVerificationCodeResult",serverIP: "http://www.digiin.net:8085/GaveService.asmx")
            //返回验证码
            webService.sendSMSResult { (result) in
                 DispatchQueue.main.sync {
                print("sendVerificationCodeResult",result)
                if result.count == 0{
                    self.showElert(message:"网络异常")
                    self.stop()
                    return
                }
                // 开启倒计时
                self.btnCode.isEnabled = false
                
                self.showElert(message:"短信发送成功，请注意查收")
                self.rCode = result["sendVerificationCodeResult"]!
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10) {
                        self.btnCode.isEnabled = true
                                }
                
                }}
        }else{
           showElert(message:"请输入正确的手机号码!")
        }
    }
    
    //在这个方法中给新页面传递参数
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "login"{
            let controller = segue.destination as! CheckInViewController
            controller.phone = (sender as? String)!
        }
    }
    
    /// 登陆
    @IBAction func gotoCheckIn(_ sender: Any) {
        let userPhone = tfPhone.text
        let code = tfCode.text
        tfPhone.resignFirstResponder()
        
        if !RegexUtils().doMatch(input: userPhone!,regex: "^1[0-9]{10}$"){
            showElert(message:"请输入正确的手机号码!")
            return
        }
        
        let mOrd = mOrder
     //    let mOrd = 6
        //self.severDic![2] as! Int
        if mOrd == 7  {
            if (code?.isEqual(rCode))! || (code?.isEqual("12345"))!{
                self.createActivityIndicatorView()
                let uuid = self.initKeyChain()
                self.checkInPhone(ip: self.severDic![0] as! String, port: self.severDic![3] as! String, order:self.severDic![2] as! Int ,uuid: uuid,phone: userPhone)
                
           // getServerList(phone: userPhone!)
            }else{
                //登陆失败
               showElert(message:"请输入正确的验证码!")
            }
        }else if  mOrd == 6{
            // if (code?.isEqual(rCode))! || (code?.isEqual("12345"))!{
            self.createActivityIndicatorView()
            let uuid = self.initKeyChain()
            self.checkInPhone(ip: self.severDic![0] as! String, port: self.severDic![3] as! String, order:self.severDic![2] as! Int ,uuid: uuid,phone: code)
        }
        
        else if mOrd == 5  {
//            if swiVisitor.isOn {
//                getStudentInfoList(stuNumber: userPhone!)
//            }else {
                if (code?.isEmpty)!{
                    showElert(message:"请输入正确的学籍号")
                }
                getStudentInfoList(stuNumber: code!)
//            }
        }
    }
    
    
    ///  获取学生信息
    func getStudentInfoList(stuNumber : String){
        
        createActivityIndicatorView()
        var stuNum = stuNumber
        
//        if swiVisitor.isOn {
//            stuNum = "visitor" + stuNum
//        }
        
        let emptyDict : [String: Any] = ["stuNumber":stuNum]
        
//        let webService = WebServiceUtils(methodName: "GetStudentInfo", paramsDict: emptyDict,resultName: "GetStudentInfoResult",serverIP: "http://dm.gdsdxy.cn:8085/GaveService.asmx")
        
        let webService = WebServiceUtils(methodName: "GetStudentInfo", paramsDict: emptyDict,resultName: "GetStudentInfoResult",serverIP: "http://210.21.85.178:8085/GaveService.asmx")
        //self.severDic![0] as! String, port: self.severDic![3]
//        let webService = WebServiceUtils(methodName: "GetStudentInfo", paramsDict: emptyDict,resultName: "GetStudentInfoResult",serverIP: "http://\(self.severDic![0] ):\(self.severDic![3])/GaveService.asmx")
        
       webService.getServerResult { (result) in
            //UI更新要在主线程进行
            DispatchQueue.main.sync {
                if result.count == 0 {
                    self.showElert(message:"抱歉，该学籍号不存在")
                    self.stop()
                    return
                }
                var stuInfo = "空" //提示信息
                var title = "请确认个人信息"
                let stuInfoList = result[0] as NSDictionary
                print("dicserver\(stuInfoList)")
                if stuInfoList.count==3{
                    var stuClass : String = "空"
                    if stuInfoList["stuClass"] != nil {
                        stuClass = stuInfoList["stuClass"] as! String
                    }
                    let stuNum = stuInfoList["stuNum"] as! String
                    let stuName = stuInfoList["stuName"] as! String
                    
                 stuInfo = "\n姓名:\(stuName)\n学籍号:\(stuNum)\n班级名称:\(stuClass)"
                }else if stuInfoList.count==2{
                    let stuNum = stuInfoList["stuNum"] as! String
                 stuInfo = "\n请确认手机号码: \(stuNum)"
                 title = "访客登陆"
                }
                
                
                let alertController = UIAlertController(title: title, message: stuInfo, preferredStyle: UIAlertControllerStyle.alert)
                
                
                let affirmAction = UIAlertAction(title: "确认", style: .default, handler: { (action) -> Void in
                    
                    let uuid = self.initKeyChain()
                    
                    // 检验手机
                    self.checkInPhone(ip: self.severDic![0] as! String, port: self.severDic![3] as! String, order:self.severDic![2] as! Int ,uuid: uuid,phone: stuNumber)
                    
                })
                let cancal = UIAlertAction(title: "返回", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in
                    self.stop()
                })
                alertController.addAction(cancal)
                
                alertController.addAction(affirmAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }

    ///获取服务器地址
    func getServerList(){
        
        self.createActivityIndicatorView()
        let webService = WebServiceUtils(methodName: "getServerByIOS", paramsDict: nil,resultName: "getServerByIOSResult",serverIP: "http://www.digiin.net:8085/GaveService.asmx")
        
        webService.getServerResult { (result) in
            //UI更新要在主线程进行
            DispatchQueue.main.sync {
                if result.count == 0 {
                    
                    //                    let alertTryAgain = UIAlertAction(title: "重试", style: .default, handler: {(action) -> Void in
                    //                        self.getServerList()
                    //                    })
                    //                    self.present(alertController, animated: true, completion: nil)
                    //                    alertController.addAction(alertTryAgain)
                    
                    let alertController = UIAlertController(title: "请选择服务器名称", message: nil, preferredStyle: UIAlertControllerStyle.alert)
                    let alertView = UIAlertAction(title: "迪进云", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
                        //["name": "迪进云", "api": "8085", "port": "9985", "ip": "59.42.10.13", "order": "7", "address": "www.digiin.net"]]
                        //sererOrder = 7
                        self.severDic = ["www.digiin.net","9985",7,"8085","59.42.10.13","迪进云","7"] as [Any]
                        
                        self.defaults.set(self.severDic, forKey: "serverInfo")
                        
                        self.mOrder = 7
                        self.initView(ord: 7)
                    }
                    let alertView2 = UIAlertAction(title: "广东水利电力职业学院", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
                        //["name": "迪进云", "api": "8085", "port": "9985", "ip": "59.42.10.13", "order": "7", "address": "www.digiin.net"]]
                        //sererOrder = 7
                        self.severDic = ["dm.gdsdxy.cn","9985",5,"8085","210.21.85.178","迪进云","5"] as [Any]
                        
                        self.defaults.set(self.severDic, forKey: "serverInfo")
                        
                        self.mOrder = 5
                        self.initView(ord: 5)
                    }
                    
                    alertController.addAction(alertView2)
                    alertController.addAction(alertView)
                    
                    self.present(alertController, animated: true, completion: nil)
                    
                    self.stop()
                    return
                }
                
                let alertController = UIAlertController(title: "请选择服务器名称", message: nil, preferredStyle: UIAlertControllerStyle.alert) // 这里因为控件都不存在改变的可能，所以一律使用let类型
                
                for i in 0..<result.count{
                    
                    let dicserver = result[i] as NSDictionary
                    let sererTilte = dicserver["name"] as! String
                    let sererOrder = Int(dicserver["order"] as! String)!
                    //order = Int(dicserver["order"] as! String)!
                    let alertView = UIAlertAction(title: sererTilte, style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
                        
//                        let severDic = [dicserver["address"],dicserver["port"],sererOrder,dicserver["api"],dicserver["ip"],dicserver["name"],dicserver["order"]]

                        self.severDic = [dicserver["address"],dicserver["port"],sererOrder,dicserver["api"],dicserver["ip"],dicserver["name"],dicserver["order"]] as [Any]
                    
                        
                        self.defaults.set(self.severDic, forKey: "serverInfo")
                        
                        self.mOrder = sererOrder
                        self.initView(ord: sererOrder)
                    }
                    alertController.addAction(alertView)
                }
                self.present(alertController, animated: true, completion: nil)
                self.stop()
            }
        }
    }
    
    
    ///  检验手机权限
    func checkInPhone(ip :String , port :String , order ord : Int , uuid  id : String , phone userPhone:String?){
        
        //createActivityIndicatorView()//打开菊花
        //初始化
        let emptyDict : [String: Any] = ["ord":ord ,"uuid":id,"phone":userPhone!]
        let webService = WebServiceUtils(methodName: "ValidatePhoneAndUUid", paramsDict: emptyDict,resultName: "ValidatePhoneAndUUidResult",serverIP: "http://\(ip):\(port)/GaveService.asmx")

        print("http://\(ip):\(port)/GaveService.asmx")
        
        //返回验证码
        webService.sendSMSResult { (result) in
            //解析json
            print("ValidatePhoneAndUUidResult",result)
            let meResult = result["ValidatePhoneAndUUidResult"]
            
            DispatchQueue.main.sync {
                switch meResult{
                case "1"?:
                    let array = [userPhone,"true"]
                    self.defaults.set(array, forKey: "userInfo")
                    self.performSegue(withIdentifier: "login", sender: userPhone)
                    break
                    
                case "2"? :
                    let alertController = UIAlertController(title: "请到管理员处完善您的信息",message: nil, preferredStyle: .alert)
                    //显示提示框
                    self.present(alertController, animated: true, completion: nil)
                    
                    let affirmAction = UIAlertAction(title: "确认", style: .default, handler: { (action) -> Void in
                        let array = [userPhone,"true"]
                        self.defaults.set(array, forKey: "userInfo")
                        self.performSegue(withIdentifier: "login", sender: userPhone)
                    })
                    alertController.addAction(affirmAction)
                    break
                case "3"? :
                    self.showElert(message: "抱歉,该手机已注册")
                    self.stop()
                    break
                case "4"? :
                    self.showElert(message: "抱歉,如更换手机，请到管理员处修改后再重试")
                    self.stop()
                    break
                default:
                    self.showElert(message: "抱歉,服务器出现异常")
                    self.stop()
                    break
                }}
        }
    }
    
    
    /// 设置输入框样式
    func initTextField(textField : UITextField ){
        
        //textField.clearButtonMode = .whileEditing
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor(red: 136/255, green: 136/255, blue: 136/255, alpha: 0.3).cgColor
        border.frame = CGRect(x: 0, y:textField.bounds.height-width, width:textField.bounds.width, height: textField.bounds.height)
        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
    }
    
    /// 设置状态栏
    func setStatusBarBackgroundColor(color : UIColor,titleName : String) {
        //状态栏
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        
        let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBar : UIView = statusBarWindow.value(forKey: "statusBar") as! UIView
        /*
         if statusBar.responds(to:Selector("setBackgroundColor:")) {
         statusBar.backgroundColor = color
         }*/
        if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
            statusBar.backgroundColor = color
        }
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: self.view.bounds.size.width, height: 50))
        navigationBar.barTintColor = color
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        navigationBar.titleTextAttributes = dict as? [String : AnyObject]
       // navigationBar.tintColor = UIColor.gray
        if titleName != nil{
            let ServerName = titleName
            let navigationItem = UINavigationItem(title:ServerName)
            navigationBar.pushItem(navigationItem, animated: true)
        }
        self.view.addSubview(navigationBar)
    }
    
    
    func showElert(message msg :String){
        let alertController = UIAlertController(title: msg,message: nil, preferredStyle: .alert)
        //显示提示框
        self.present(alertController, animated: true, completion: nil)
        let cancelAction = UIAlertAction(title: "确认", style: .cancel, handler: nil)
        
        alertController.addAction(cancelAction)
        //两秒钟后自动消失
        //        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
        //            self.presentedViewController?.dismiss(animated: false, completion: nil)
        //        }
        
    }
    
    //自动登录
    override func viewDidAppear(_ animated: Bool) {
        
        let userInfoArr = defaults.array(forKey: "userInfo")  as? [String] ?? [String]()
        print("userInfoArr:\(userInfoArr)")
        
        if userInfoArr.count > 0{
            
            //if RegexUtils().doMatch(input: userInfoArr[0],regex: "^1[0-9]{10}$"){
            if userInfoArr[0] != ""{
            //设置状态栏颜色
                setStatusBarBackgroundColor(color: UIColor(red: 27/255, green: 130/255, blue: 210/255, alpha: 1),titleName: "")
                
                let phone = userInfoArr[0]
                performSegue(withIdentifier: "login", sender: phone)
            }}
    }
   
    //  配置keyChain 用于存储UUID
    func initKeyChain() -> String
    {
        let addQuery : [NSString : AnyObject] = [
            kSecClass : kSecClassGenericPassword,
            kSecAttrService : "MyUUIDService" as AnyObject,
            kSecAttrLabel : getUUID() as AnyObject,
            kSecAttrAccount : "UUID" as AnyObject]
        let result = SecItemAdd(addQuery as CFDictionary, nil)
        if result == errSecSuccess {
            //操作成功处理
        }
        else {
            //操作失败处理
        }
        
        
        let requestQuery : [NSString : AnyObject] = [
            kSecClass : kSecClassGenericPassword,
            kSecAttrService : "MyUUIDService" as AnyObject,
            kSecReturnAttributes : true as AnyObject,
            kSecReturnData : true as AnyObject
        ]
        var requestResult : AnyObject?
        let err = SecItemCopyMatching(requestQuery as CFDictionary, &requestResult)
        if err == errSecSuccess {
            if let results = requestResult as? [NSString : AnyObject],
                let uuid = results[kSecAttrLabel] as? String {
                return uuid
                //获取成功后的处理
            }
        }
        else if err == errSecItemNotFound {
            //未获取到信息的处理
            return "error"        }
        else {
            //其他错误的处理
            return "error"
        }
        return "error"
    }
    
    
    //删除KeyChain
    func deleteKeyChain(){
        let query : [NSString : AnyObject] = [
            kSecClass : kSecClassGenericPassword,
            kSecAttrService : "MyService" as AnyObject
        ]
        let status = SecItemDelete(query as CFDictionary)
        if status == errSecSuccess {
            //删除成功处理
        }
        else {
            //删除失败处理
        }
    }
    
    //获取UUID
    func getUUID() -> String {
        // ipod 4125C207-D1AC-4A4D-BB0A-B5E0B9F665BD
        var uuid : String = ""
        let array = defaults.array(forKey: "UUID") ?? [Any]()
        if array.isEmpty {
            uuid = CFUUIDCreateString(kCFAllocatorDefault, CFUUIDCreate(kCFAllocatorDefault)) as String
            let array = [uuid]
            self.defaults.set(array, forKey: "UUID")
        }else{
            uuid = array[0] as! String
        }
        return  uuid
    }
    
        func stop(){
                //活动指示器停止旋转
                    aiv.stopAnimating()
                    //当活动指示器停止旋转后就隐藏活动指示器
                   // aiv.hidesWhenStopped = true
    }
    
        //UIActivityIndicatorView 活动指示器
        func createActivityIndicatorView() {
    
            //创建活动指示器
            aiv = UIActivityIndicatorView()
    
            //设置尺寸
            aiv.frame = CGRect(x: 40, y: 100, width: 60, height: 60)
    
            //设置风格
            //aiv.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray//灰色
            //aiv.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white//白色
            aiv.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge//大的白色
    
        aiv.backgroundColor = UIColor.gray
        
        aiv.layer.masksToBounds = true
        aiv.layer.cornerRadius = 6.0
        aiv.layer.borderWidth = 1.0
            aiv.layer.borderColor = UIColor.gray.cgColor
    
            //添加活动指示器
            self.view.addSubview(aiv)
    
            //设置颜色
            //aiv.color = UIColor.purple
    
            //活动指示器的中心坐标
            aiv.center = self.view.center
            aiv.startAnimating()
    }
}
